package com.hhd.pdf.components.branch;

import com.hhd.pdf.CommonUtils;
import com.hhd.pdf.variable.VariableContext;
import org.dom4j.Attribute;
import org.dom4j.Element;

import java.util.List;
import java.util.stream.Collectors;

public class HasBranch {
    public static boolean has(Element element, VariableContext variableContext) {
        List<Attribute> attributes = element.attributes();

        attributes = attributes.stream()
                .filter(HasBranch::isHasVariableName)
                .collect(Collectors.toList());
        if (CommonUtils.isEmpty(attributes)) return true;
        return doHasCondition(variableContext, attributes, getCondition(element));
    }

    private static boolean doHasCondition(VariableContext variableContext, List<Attribute> attributes, HasCondition condition) {
        boolean res = variableContext.has(attributes.get(0).getValue());
        for (int i = 1; i < attributes.size(); i++) {
            Attribute attribute = attributes.get(i);
            boolean has = variableContext.has(attribute.getValue());
            if (condition == HasCondition.and) {
                res = has && res;
            } else {
                res = has || res;
            }
        }

        return res;
    }

    private static HasCondition getCondition(Element element) {
        String hasCondition = element.attributeValue("hasCondition");
        return HasCondition.forName(hasCondition);
    }

    private static boolean isHasVariableName(Attribute attribute) {
        if("hasCondition".equals(attribute.getName())) return false;
        return attribute.getName().startsWith("has");
    }

    enum HasCondition {
        or, and;

        public static HasCondition forName(String hasCondition) {
            if (CommonUtils.isEmpty(hasCondition)) return HasCondition.or;
            if ("and".equals(hasCondition)) return and;
            if ("or".equals(hasCondition)) return or;
            throw new RuntimeException("不支持的hasCondition:" + hasCondition);
        }
    }
}
